package com.scanner.scannersdk;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.scanner.scannersdk.callback.SdkMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.UUID;


public class SppBlueToothServce extends Service {
    private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothServerSocket bluetoothServerSocket;
    private BluetoothDevice bluetoothDevice;
    private BluetoothSocket bluetoothSocket;
    private OutputStream outputStream;
    private Thread thread_thread;
    private boolean stop_read;

    private Boolean first = true;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bluetoothDevice = intent.getParcelableExtra("bluetoothDevice");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        connectBlueDevce();
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    //蓝牙连接
    private void connectBlueDevce() {
            thread_thread = new Thread(){
                @Override
                public void run() {
                    try {
                        Looper.prepare();
                        bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
                        bluetoothSocket.connect();
                        outputStream = bluetoothSocket.getOutputStream();
                    }catch (IOException e){
                        EventBus.getDefault().post(SdkMessage.getInstance(null,SdkValue.connectbt_fail,null));
                        interrupt();
                    }
                    EventBus.getDefault().post(SdkMessage.getInstance(null,SdkValue.connectbt_success,null));
                    stop_read = false;
                    byte[] buffer = new byte[1024];
                    int bytes;
                    InputStream mmInStream = null;   //建立输入流读取数据
                    try {
                        mmInStream = bluetoothSocket.getInputStream();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    while (true && !stop_read) {  //无限循环读取数据
                        try {
                            if ((bytes = mmInStream.read(buffer)) > 0) {
                                byte[] buf_data = new byte[bytes];
                                for (int i = 0; i < bytes; i++) {
                                    buf_data[i] = buffer[i];
                                }

                                if (buf_data != null && buf_data.length != 0) {
                                    Log.d("netumsdk","接收到数据"+Arrays.toString(buf_data));
                                    EventBus.getDefault().post(SdkMessage.getInstance(null, SdkValue.SdkMessageType_Receve, buf_data));
                                }
                            }

                        } catch (IOException e) {
                            break;  //异常的时候break跳出无限循环
                        }
                    }


                    //在刚连接时，发一条延迟的消息去查询模组信息
                    if (first) {
                        CountDownTimer countDownTimer = new CountDownTimer(500, 500) {
                            @Override
                            public void onTick(long millisUntilFinished) {

                            }

                            @Override
                            public void onFinish() {
                                try {
                                    outputStream.write(ScannerUtil.getCommandBtye(SdkValue.MODE_STYLE));
                                    outputStream.flush();
                                } catch (IOException e) {

                                }
                            }
                        }.start();
                        first = false;
                    }
                }
            };
            thread_thread.start();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendCommand(SdkMessage sdkMessage) {
        switch (sdkMessage.type) {
            case SdkValue.SdkMessageType_Send:
                if (bluetoothSocket.isConnected()) {
                    try {
                        Log.d("tag", Arrays.toString(sdkMessage.s));
                        outputStream.write(sdkMessage.s);
//                        outputStream.write(new byte[]{0X02,0x08,0x0A,0x25,0x25,0x30,0x50,(byte) 0XFD,(byte) 0xEB,0X03});
                        outputStream.flush();
                    } catch (IOException e) {
                        Toast.makeText(this, "The command failed to send and the Bluetooth connection has been disconnected", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(this, "The command failed to send and the Bluetooth connection has been disconnected", Toast.LENGTH_SHORT).show();
                }
                break;
            case SdkValue.getSdkMessageType_DisSppBluetoothAndServce:
                try {
                    bluetoothSocket.close();
                    EventBus.getDefault().unregister(this);
                } catch (IOException e) {
                    Toast.makeText(this, "关闭连接失败", Toast.LENGTH_SHORT).show();
                }
                stop_read = true;
                stopSelf();
                break;
        }
    }
}
